package com.serkol.ams.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaLiveService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.serkol.ams.bean.*;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.entity.Users;
import com.serkol.ams.entity.UsersAuthentication;
import com.serkol.ams.service.*;
import com.serkol.annotation.IsLogin;
import com.serkol.component.SystemSettingUtils;
import com.serkol.component.TokenUtils;
import com.serkol.config.I18nUtil;
import com.serkol.config.WebSocketDeviceServer;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.constant.ResultConstant;
import com.serkol.exception.AuthException;
import com.serkol.exception.SerkolProjectException;
import com.serkol.handler.ParseUtils;
import com.serkol.utils.LangValidUtils;
import com.serkol.utils.OrderUtils;
import com.serkol.wx.bean.AgentSuccessMsg;
import com.serkol.wx.service.WeChatPayService;
import com.serkol.wx.service.WechatMiniMessageService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("api/oauth/login")
public class LoginApiController {


    @Autowired
    private UsersService userService;


    @Autowired
    private UsersAuthenticationService usersAuthenticationService;

    @Autowired
    private AgentService agentService;

    private TokenUtils tokenUtils;
    @Autowired
    private LoginLogService logService;

    @Autowired
    private UsersInvitationRelationshipService invitationRelationshipService;

    @Autowired
    private WebSocketDeviceServer webSocketDeviceServer;

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WeChatPayService weChatPayService;

    @Autowired
    private SystemSettingUtils systemSettingUtils;
    @Autowired
    private WechatMiniMessageService wechatMiniMessageService;

    @Value("${upload.path}")
    private String uploadpath;
    @Value("${upload.host}")
    private String uploadhost;
    /**
     * 获取客户端ip地址
     *
     * @param request
     * @return
     */
    public static String getCliectIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

    @PostMapping("/wxTestMsg")
    @ResponseBody
    public Result wxTestMsg() {
        AgentSuccessMsg agentSuccessMsg = new AgentSuccessMsg();
        agentSuccessMsg.setName("代理平台");
        agentSuccessMsg.setGoodsName("产品名称");
        agentSuccessMsg.setAgentCommission(BigDecimal.valueOf(10));
        agentSuccessMsg.setRetailPrice(BigDecimal.valueOf(100));
        agentSuccessMsg.setSupplyPrice(BigDecimal.valueOf(10));

        try {
            wechatMiniMessageService.sendMessage(agentSuccessMsg);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        System.out.println("Hello");
        return Result.ok();
    }

    @PostMapping("/wxTest")
    @ResponseBody
    public Result wxTest(HttpServletRequest request, @RequestBody @Valid WxMiniConfig wxMiniConfig) throws SerkolProjectException, WxErrorException {
        tokenUtils = new TokenUtils(logService);
        System.out.println(wxMiniConfig);
        LoginLog loginLog = wxMiniConfig.getLoginLog();
        // loginLog.setIp(getCliectIp(request));
        Result result = new Result();

/*
        loginLog.setIp(getCliectIp(request));
        String openid = "o7eTd4pqafII42mNJ-eUMGiA237A";
        String sessionKey = "Test";
        System.out.println(openid);
        System.out.println(wxMiniConfig);
        Users byLogin = userService.findByLogin(openid);
        Map<String, Object> mapLogin = new HashMap<>();

        mapLogin = getToken(byLogin, loginLog, sessionKey);
        result.setData(mapLogin);
        result.setStatus(ResultConstant.SUCSESS);*/

        //   wxMaService.getUserService().
        //   result.setStatus(ResultConstant.TOKEN);
        return Result.failure();
    }

    @PostMapping("/account")
    public Result account(HttpServletRequest request,@RequestBody LoginConfig loginConfig ) throws SerkolProjectException, AuthException {
        System.out.println("account");
       // System.out.println(jsonObject);
      //  LoginConfig loginConfig =jsonObject.toJavaObject(LoginConfig.class);
  //    loginConfig.setUserName("18099746017");
   //   loginConfig.setPassword("123456");
        tokenUtils = new TokenUtils(logService);
        System.out.println(request.getQueryString());
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 遍历 Map 处理每个参数
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String paramName = entry.getKey();
            String[] paramValues = entry.getValue();

            // 根据需要处理 paramValues，例如打印或进一步逻辑处理
            System.out.println("Parameter Name: " + paramName + ", Values: " + Arrays.toString(paramValues));
        }
        String agent = request.getHeader("User-Agent");
        String myLanguage = request.getHeader("MyLanguage");
        String myVersion = request.getHeader("Version");
        String terminal = request.getHeader("terminal");

        String localName = request.getLocale().getDisplayLanguage();
//解析agent字符串
        UserAgent userAgent = UserAgent.parseUserAgentString(agent);
//获取浏览器对象
        Browser browser = userAgent.getBrowser();
//获取操作系统对象
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();

        System.out.println("浏览器名:" + browser.getName());
        System.out.println("浏览器类型:" + browser.getBrowserType());
        System.out.println("浏览器家族:" + browser.getGroup());
        System.out.println("浏览器生产厂商:" + browser.getManufacturer());
        System.out.println("浏览器使用的渲染引擎:" + browser.getRenderingEngine());
        System.out.println("浏览器版本:" + userAgent.getBrowserVersion());

        System.out.println("操作系统名:" + operatingSystem.getName());
        System.out.println("访问设备类型:" + operatingSystem.getDeviceType());
        System.out.println("操作系统家族:" + operatingSystem.getGroup());
        System.out.println("操作系统生产厂商:" + operatingSystem.getManufacturer());
        System.out.println(loginConfig);
        LoginLog loginLog = new LoginLog();
        loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setMyLanguage(myLanguage);
        loginLog.setMyVersion(myVersion);
        loginLog.setLanguage(localName);
        loginLog.setBrand(operatingSystem.getManufacturer().getName());
        loginLog.setModel(operatingSystem.getName());
        loginLog.setSystemVersion(browser.getName());
      //  loginLog.setVersion(userAgent.getBrowserVersion().getVersion());
        loginLog.setIp(getCliectIp(request));
        Result result = new Result();
        //   DevicePlatform devicePlatform = device.getDevicePlatform();
        loginLog.setPlatform(operatingSystem.getDeviceType().getName());

        Users byLogin = userService.findByUserLogin(loginConfig);
        if (byLogin.getIsAdmin() == 1) {
            Map<String, Object> mapLogin = new HashMap<>();
            if (byLogin != null) {
                loginLog.setOpenId(byLogin.getOpenid());
                mapLogin = getToken(byLogin, loginLog, "");
                result.setData(mapLogin);
                result.setStatus(ResultConstant.SUCSESS);
                return result;
            } else {
                throw new AuthException(ResultCode.OK_CONTENT_NO);
            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_UNAUTHORIZED);
        }


    }


    @PostMapping("/accountWechat")
    @ResponseBody
    public Result accountWechat(HttpServletRequest request, @RequestBody @Valid WxLoginConfig loginConfig) throws SerkolProjectException, AuthException {
        tokenUtils = new TokenUtils(logService);

        //   String terminal = request.getHeader("terminal");
        Result result = new Result();
        LoginLog loginLog = loginConfig.getLoginLog();
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        Users byLogin = userService.findByUserLogin(loginConfig);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            loginLog.setOpenId(byLogin.getOpenid());
            if (loginConfig.getParentUserId() != null) {
                boolean isUser = userService.isUsers(loginConfig.getParentUserId());
                if (isUser) {
                    byLogin.setParentUserId(loginConfig.getParentUserId());
                    if (loginConfig.getParentUserId() != null) {
                        invitationRelationshipService.invalidUsers(byLogin.getId(), loginConfig.getParentUserId());
                    }
                }

            }
            mapLogin = getToken(byLogin, loginLog, "");
            result.setData(mapLogin);
            result.setStatus(ResultConstant.SUCSESS);
            return result;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.userorpasserror");
        }


    }


    @PostMapping("/accountWechatMiniOpen")
    @ResponseBody
    public Result accountWechatMiniOpen(HttpServletRequest request, @RequestBody @Valid WxLoginMiniConfig loginConfig) throws SerkolProjectException, AuthException, WxErrorException {
        tokenUtils = new TokenUtils(logService);
        //     String terminal = request.getHeader("terminal");
        Result result = new Result();
        LoginLog loginLog = loginConfig.getLoginLog();
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        Users byLogin = userService.findByUserLogin(loginConfig);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            System.out.println(wxMaService.getWxMaConfig().getAppid());
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(loginConfig.getCode());
            String openid = session.getOpenid();
            String sessionKey = session.getSessionKey();
    userService.byUsersDeleteOpenId(openid);
            System.out.println(openid);
            System.out.println(loginConfig);
            loginLog.setOpenId(byLogin.getOpenid());
            if (loginConfig.getParentUserId() != null) {
                boolean isUser = userService.isUsers(loginConfig.getParentUserId());
                if (isUser) {
                    byLogin.setParentUserId(loginConfig.getParentUserId());
                    if (loginConfig.getParentUserId() != null) {
                        invitationRelationshipService.invalidUsers(byLogin.getId(), loginConfig.getParentUserId());
                    }
                }

            }
            if (StringUtils.isEmpty(byLogin.getInvite())) {
                String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                byLogin.setInvite(invalidCode);
            }

            byLogin.setOpenid(openid);
            userService.updateById(byLogin);

            loginLog.setOpenId(byLogin.getOpenid());
            mapLogin = getToken(byLogin, loginLog, sessionKey);
            if (loginConfig.getParentUserId() != null) {
                invitationRelationshipService.invalidUsers(byLogin.getId(), loginConfig.getParentUserId());
            }
            //   wxMaService.getUserService().setUserStorage(mapText, sessionKey, openid);
            result.setData(mapLogin);
            result.setStatus(ResultConstant.SUCSESS);

            return result;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.userorpasserror");
        }


    }

    @PostMapping("/accountWechatMini")
    @ResponseBody
    public Result accountWechatMini(HttpServletRequest request, @RequestBody @Valid WxLoginMiniConfig loginConfig) throws SerkolProjectException, AuthException, WxErrorException {
        tokenUtils = new TokenUtils(logService);
        //     String terminal = request.getHeader("terminal");
        Result result = new Result();
        LoginLog loginLog = loginConfig.getLoginLog();
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        Users byLogin = userService.findByUserLogin(loginConfig);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            System.out.println(wxMaService.getWxMaConfig().getAppid());
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(loginConfig.getCode());
            String openid = session.getOpenid();
            userService.byUsersDeleteOpenId(openid);
            String sessionKey = session.getSessionKey();
            System.out.println(openid);
            System.out.println(loginConfig);
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, loginConfig.getEncryptedData(), loginConfig.getIv());
            if (userInfo != null) {
                loginLog.setOpenId(byLogin.getOpenid());

                Users usersDetail = ParseUtils.parseUsersDetail(userInfo);

                usersDetail.setOpenid(openid);
                if (loginConfig.getParentUserId() != null) {
                    boolean isUser = userService.isUsers(loginConfig.getParentUserId());
                    if (isUser) {
                        byLogin.setParentUserId(loginConfig.getParentUserId());
                        if (loginConfig.getParentUserId() != null) {
                            invitationRelationshipService.invalidUsers(byLogin.getId(), loginConfig.getParentUserId());
                        }
                    }

                }

                if (StringUtils.isEmpty(byLogin.getInvite())) {
                    String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                    byLogin.setInvite(invalidCode);
                }
                byLogin.setAvatar(userInfo.getAvatarUrl());
                byLogin.setNickname(userInfo.getNickName());
                byLogin.setSex(Integer.parseInt(userInfo.getGender()));
                // usersDetail.set(wxMaUserInfo.getCity());
                //   usersDetail.setCountry(wxMaUserInfo.getCountry());
                //  usersDetail.setLanguage(wxMaUserInfo.getLanguage());
                //  usersDetail.setOpenid(wxMaUserInfo);
                byLogin.setUnionid(userInfo.getUnionId());
                byLogin.setOpenid(openid);
                userService.updateById(byLogin);

                loginLog.setOpenId(byLogin.getOpenid());
                mapLogin = getToken(byLogin, loginLog, sessionKey);
                if (loginConfig.getParentUserId() != null) {
                    invitationRelationshipService.invalidUsers(byLogin.getId(), loginConfig.getParentUserId());
                }
                //   wxMaService.getUserService().setUserStorage(mapText, sessionKey, openid);
                result.setData(mapLogin);
                result.setStatus(ResultConstant.SUCSESS);

            } else {
                result.setStatus(ResultConstant.FAIL);
            }
            return result;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.userorpasserror");
        }


    }


    @IsLogin
    @PostMapping("/refreshLogin")
    @ResponseBody
    public Result refreshLogin(HttpServletRequest request) throws SerkolProjectException, AuthException {
        tokenUtils = new TokenUtils(logService);
        Result result = new Result();
        LoginLog loginLog = AuthConstant.getLoginLog();
        loginLog.setIp(getCliectIp(request));
        Users byLogin = userService.findByUserId(loginLog.getUserId());
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            loginLog.setId(null);
            loginLog.setOpenId(byLogin.getOpenid());
            mapLogin = getToken(byLogin, loginLog, "");
            result.setData(mapLogin);
            result.setStatus(ResultConstant.SUCSESS);
            return result;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO);
        }


    }
    @IsLogin
    @PostMapping("/getWxSessionKey")
    @ResponseBody
    public Result getWxSessionKey(@RequestBody JSONObject data) throws WxErrorException, AuthException {
        final String code = data.getString("code");
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        String sessionKey = session.getSessionKey();
        return Result.ok(sessionKey);
    }

    @PostMapping("/miniLogin")
    @ResponseBody
    public Result miniLogin(HttpServletRequest request) throws SerkolProjectException, AuthException {
        tokenUtils = new TokenUtils(logService);
        //   String terminal = request.getHeader("terminal");
        Result result = new Result();
        LoginLog loginLog = AuthConstant.getLoginLog();
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        Users byLogin = userService.findByUserId(loginLog.getUserId());
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            loginLog.setOpenId(byLogin.getOpenid());
            mapLogin = getToken(byLogin, loginLog, "");
            result.setData(mapLogin);
            result.setStatus(ResultConstant.SUCSESS);
            return result;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.userorpasserror");
        }


    }

    @PostMapping("/wxMini")
    @ResponseBody
    public Result wxMini(HttpServletRequest request, @RequestBody @Valid WxMiniConfig wxMiniConfig) throws SerkolProjectException, WxErrorException {
        tokenUtils = new TokenUtils(logService);
        String terminal = request.getHeader("terminal");
        System.out.println(wxMiniConfig);
        LoginLog loginLog = wxMiniConfig.getLoginLog();
        loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        // loginLog.setIp(getCliectIp(request));
        Result result = new Result();
        String agendefaultid = systemSettingUtils.getInfo("agendefaultid");


        loginLog.setIp(getCliectIp(request));

        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniConfig.getCode());
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        userService.byUsersDeleteOpenId(openid);
        System.out.println(openid);
        System.out.println(wxMiniConfig);
        Users byLogin = userService.findByLogin(openid);

        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin == null) {
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, wxMiniConfig.getEncryptedData(), wxMiniConfig.getIv());

            System.out.println(userInfo);
            if (userInfo != null) {

                Users usersDetail = ParseUtils.parseUsersDetail(userInfo);
                if (agendefaultid != null && byLogin.getAgentId() == null && byLogin.getStatus() == 0) {
                    Long agentIdDefault = Long.valueOf(agendefaultid);
                    usersDetail.setAgentId(agentIdDefault);
                }
                usersDetail.setOpenid(openid);
                if (wxMiniConfig.getParentUserId() != null) {
                    boolean isUser = userService.isUsers(wxMiniConfig.getParentUserId());
                    if (isUser) {
                        usersDetail.setParentUserId(wxMiniConfig.getParentUserId());

                    }
                } else {
                    result.setStatus(ResultConstant.FAIL);
                    return result;
                }
                byLogin = userService.findByLoginAndInsert(usersDetail);
                String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                byLogin.setInvite(invalidCode);
                userService.updateById(byLogin);
                loginLog.setOpenId(byLogin.getOpenid());
                mapLogin = getToken(byLogin, loginLog, sessionKey);
                if (wxMiniConfig.getParentUserId() != null) {
                    invitationRelationshipService.invalidUsers(byLogin.getId(), wxMiniConfig.getParentUserId());
                }
                //   wxMaService.getUserService().setUserStorage(mapText, sessionKey, openid);
                result.setData(mapLogin);
                result.setStatus(ResultConstant.SUCSESS);
            } else {
                result.setStatus(ResultConstant.FAIL);
            }
            //  wxMaService.getUserService().setUserStorage(map, sessionKey,openid);

        } else {
            if (wxMiniConfig.getParentUserId() != null) {
                boolean isUser = userService.isUsers(wxMiniConfig.getParentUserId());
                if (isUser) {
                    byLogin.setParentUserId(wxMiniConfig.getParentUserId());
                    userService.saveOrUpdate(byLogin);

                    invitationRelationshipService.invalidUsers(byLogin.getId(), wxMiniConfig.getParentUserId());

                }

            }
            loginLog.setOpenId(byLogin.getOpenid());
            mapLogin = getToken(byLogin, loginLog, sessionKey);
            result.setData(mapLogin);
            result.setStatus(ResultConstant.SUCSESS);
        }
        //   wxMaService.getUserService().
        return result;
    }


    @Transactional
    @PostMapping("/wxRegesterMini")
    @ResponseBody
    public Result wxRegesterMini(HttpServletRequest request, @RequestBody @Valid WxMiniRegesterConfig wxMiniConfig) throws SerkolProjectException, WxErrorException, AuthException {
        tokenUtils = new TokenUtils(logService);
        UsersRegesterInfo regesterInfo = wxMiniConfig.getRegesterInfo();
        //    String terminal = request.getHeader("terminal");
        //  System.out.println(wxMiniConfig);
        LoginLog loginLog = wxMiniConfig.getLoginLog();
        // loginLog.setIp(getCliectIp(request));
        Result result = new Result();
        Long agentIdDefault = 1L;
        String agendefaultid = systemSettingUtils.getInfo("agendefaultid");
        System.out.println("llllll:" + agendefaultid);
        if (StringUtils.isNotEmpty(agendefaultid)) {
            agentIdDefault = Long.valueOf(agendefaultid);
        }
        //    loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));

        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniConfig.getCode());
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        userService.byUsersDeleteOpenId(openid);
        System.out.println(openid);
        System.out.println(wxMiniConfig);
        Users byLogin = userService.findByLoginOrPhone(openid,regesterInfo.getPhone());
        loginLog.setOpenId(openid);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin == null) {
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, wxMiniConfig.getEncryptedData(), wxMiniConfig.getIv());
            System.out.println(userInfo);
            if (userInfo != null) {

                Users usersDetail = ParseUtils.parseUsersDetail(userInfo);
                usersDetail.setAgentId(agentIdDefault);
                usersDetail.setOpenid(openid);
                if (regesterInfo.getParentUserId() != null) {
                    boolean isUser = userService.isUsers(regesterInfo.getParentUserId());
                    if (isUser) {
                        usersDetail.setParentUserId(regesterInfo.getParentUserId());

                    }
                }
                if (StringUtils.isNotEmpty(regesterInfo.getPassword())) {
                    MD5 md5 = MD5.create();
                    String s = md5.digestHex(regesterInfo.getPassword());
                    usersDetail.setUserPassword(s);
                }
                //  usersDetail.setUserPassword(regesterInfo.getPassword());
                usersDetail.setPhone(regesterInfo.getPhone());
                //   usersDetail.setInvite("");


                byLogin = userService.findByLoginAndInsert(usersDetail);
                if (byLogin.getId() > 0) {
                    String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                    byLogin.setInvite(invalidCode);
                    byLogin.setPhone(regesterInfo.getPhone());
                    userService.updateById(byLogin);
                    UsersAuthentication usersAuthentication = new UsersAuthentication();
                    usersAuthentication.setWechat(regesterInfo.getWechat());
                    usersAuthentication.setPhone(regesterInfo.getPhone());
                    usersAuthentication.setName(regesterInfo.getName());
                    usersAuthentication.setIdcard(regesterInfo.getIdcard());
                    usersAuthentication.setUserId(byLogin.getId());
                    mapLogin = getToken(byLogin, loginLog, sessionKey);
                    if (regesterInfo.getParentUserId() != null) {
                        invitationRelationshipService.invalidUsers(byLogin.getId(), regesterInfo.getParentUserId());
                    }
                    boolean b = usersAuthenticationService.saveOrUpdate(usersAuthentication);
                    if (b) {
                        result.setData(mapLogin);
                        result.setStatus(ResultConstant.SUCSESS);
                    } else {
                        result.setStatus(ResultConstant.FAIL);
                    }
                } else {
                    result.setStatus(ResultConstant.FAIL);
                }
            } else {
                result.setStatus(ResultConstant.FAIL);
            }
            //  wxMaService.getUserService().setUserStorage(map, sessionKey,openid);

        } else {


            if (byLogin.getAgentId() == null) {
                result.setStatus(ResultConstant.FAIL);
            } else {

                if (byLogin.getAgentId() == 1) {
                    if (Objects.equals(regesterInfo.getParentUserId(), byLogin.getParentUserId()) ||regesterInfo.getParentUserId() != null && byLogin.getParentUserId() == null || regesterInfo.getParentUserId() != null && byLogin.getParentUserId() != null && regesterInfo.getUpgrade()==1) {
                        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, wxMiniConfig.getEncryptedData(), wxMiniConfig.getIv());
                        if (userInfo != null) {
                            Users usersDetail = ParseUtils.parseUsersDetail(byLogin, userInfo);
                            UsersAuthentication usersAuthentication = usersAuthenticationService.getFindByUserId(byLogin.getId());
                            if (usersAuthentication == null) {
                                usersAuthentication = new UsersAuthentication();
                            }
                            usersAuthentication.setWechat(regesterInfo.getWechat());
                            usersAuthentication.setPhone(regesterInfo.getPhone());
                            usersAuthentication.setName(regesterInfo.getName());
                            usersAuthentication.setIdcard(regesterInfo.getIdcard());
                            usersAuthentication.setUserId(byLogin.getId());

                            if (regesterInfo.getParentUserId() != null && regesterInfo.getUpgrade()!=1) {
                                invitationRelationshipService.invalidUsers(byLogin.getId(), regesterInfo.getParentUserId());
                            }
                            boolean b = usersAuthenticationService.saveOrUpdate(usersAuthentication);
                            if (b) {
                                userService.updateById(usersDetail);
                                mapLogin = getToken(usersDetail, loginLog, sessionKey);
                                result.setData(mapLogin);
                                result.setStatus(ResultConstant.SUCSESS);
                            } else {
                                result.setStatus(ResultConstant.FAIL);
                            }
                        } else {
                            throw new AuthException(ResultCode.REQUEST_ERROR_UNAUTHORIZED);
                        }
                    }else {
                        throw new AuthException(ResultCode.REQUEST_ERROR_UNAUTHORIZED);
                    }
                }else {
                    throw new AuthException(ResultCode.REQUEST_ERROR_UNAUTHORIZED);
                }
            }


        }
        //   wxMaService.getUserService().
        return result;
    }


    @PostMapping("/wxMiniAuto")
    @ResponseBody
    public Result wxMiniAuto(HttpServletRequest request, @RequestBody @Valid WxMiniConfig wxMiniConfig) throws SerkolProjectException, WxErrorException, AuthException {
        tokenUtils = new TokenUtils(logService);
        System.out.println(wxMiniConfig);


        //  String terminal = request.getHeader("terminal");
        LoginLog loginLog = wxMiniConfig.getLoginLog();
        // loginLog.setIp(getCliectIp(request));
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        System.out.println(wxMaService.getWxMaConfig().getAppid());
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniConfig.getCode());
        System.out.println(session);
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        System.out.println(openid);
        System.out.println("uniid:" +session.getUnionid());
        System.out.println(wxMiniConfig);
        Users byLogin = userService.findByLogin(openid);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {
            Long parentUserId = wxMiniConfig.getParentUserId();
            if (parentUserId != null) {
                if (byLogin.getParentUserId() == null) {
                    byLogin.setParentUserId(parentUserId);
                    userService.updateById(byLogin);
                }
            }
            loginLog.setOpenId(byLogin.getOpenid());
            mapLogin = getToken(byLogin, loginLog, sessionKey);
            return Result.ok(mapLogin);
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.regesterrecommended");
        }
        //   wxMaService.getUserService().

    }

    @PostMapping("/wxMiniCreate")
    @ResponseBody
    public Result wxMiniCreate(HttpServletRequest request, @RequestBody @Valid WxMiniConfig wxMiniConfig) throws SerkolProjectException, WxErrorException, AuthException {
        tokenUtils = new TokenUtils(logService);
        System.out.println(wxMiniConfig);
        //  String terminal = request.getHeader("terminal");
        LoginLog loginLog = wxMiniConfig.getLoginLog();
        // loginLog.setIp(getCliectIp(request));
        //  loginLog.setTerminal(NumberUtils.toInt(terminal.isEmpty() ? String.valueOf('1') : String.valueOf(terminal), 0));
        loginLog.setIp(getCliectIp(request));
        System.out.println(wxMaService.getWxMaConfig().getAppid());
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxMiniConfig.getCode());
        String openid = session.getOpenid();
        String sessionKey = session.getSessionKey();
        System.out.println(openid);
        System.out.println(wxMiniConfig);
        Users byLogin = userService.findByLogin(openid);
        Map<String, Object> mapLogin = new HashMap<>();
        if (byLogin != null) {

            return Result.failure("登录失败");
        } else {
            Long agentIdDefault = 1L;
            String agendefaultid = systemSettingUtils.getInfo("agendefaultid");
            System.out.println("llllll:" + agendefaultid);
            if (StringUtils.isNotEmpty(agendefaultid)) {
                agentIdDefault = Long.valueOf(agendefaultid);
            }

            if (openid != null && wxMiniConfig.getParentUserId()!=null) {
                Users usersDetail =new Users();
                usersDetail.setAgentId(agentIdDefault);
                usersDetail.setOpenid(openid);
                usersDetail.setNickname("新用户");

                if (wxMiniConfig.getParentUserId() != null) {
                    boolean isUser = userService.isUsers(wxMiniConfig.getParentUserId());
                    if (isUser) {
                        usersDetail.setParentUserId(wxMiniConfig.getParentUserId());

                    }
                }
                byLogin = userService.findByLoginAndInsert(usersDetail);
                if (byLogin.getId() != null) {
                    String invalidCode = OrderUtils.getInvalidCode(byLogin.getId());
                    byLogin.setInvite(invalidCode);
                    userService.updateById(byLogin);
                    mapLogin = getToken(byLogin, loginLog, sessionKey);
                    return Result.ok(mapLogin);
                } else {
                    throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.regesterrecommended");
                }
            }else {
                throw new AuthException(ResultCode.OK_CONTENT_PARTIAL, "mini.regesterrecommendedparentuserno");
            }

        }
        //   wxMaService.getUserService().

    }



    private Map<String, Object> getToken(Users usersDetail, LoginLog loginLog, String sessionKey) {
AuthConstant.setPathUrl(uploadhost);

        loginLog.setUserId(usersDetail.getId());
        loginLog.setUserName(usersDetail.getNickname());
        loginLog.setAgentId(usersDetail.getAgentId());
        loginLog.setParentUserId(usersDetail.getParentUserId());
        loginLog.setCreateDate(new Date());
        loginLog.setRoleId(usersDetail.getRoleId());
        System.out.println("--------------getToken--------------");
        System.out.println(loginLog);
        String token = tokenUtils.getToken(loginLog);

        Map<String, Object> map = ParseUtils.parseTokenDetail(usersDetail);
        UsersAuthentication authUser = usersAuthenticationService.getFindByUserId(loginLog.getUserId());
        if (authUser != null) {
            map.put("auth", true);
            if (LangValidUtils.getValid("ug")) {

                map.put("name", (StringUtils.isNotEmpty(authUser.getNameUg()) ? authUser.getNameUg() : authUser.getName()));
                map.put("nameZh", authUser.getName());
            } else {
                map.put("name", authUser.getName());
                map.put("nameZh", authUser.getName());
            }
        } else {
            map.put("name", map.get("nickName"));
        }
        map.put("admin", usersDetail.getIsAdmin());
        map.put("token", token);
        map.put("sessionKey", sessionKey);
        String message = I18nUtil.getMessage("system.company");
        if (usersDetail.getParentUserId() != null) {
            Users parentUser = userService.findByUserId(usersDetail.getParentUserId());
            System.out.println("PARENT_USER");
            System.out.println(parentUser);
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", 0);
            if (parentUser == null) {

                userMap.put("nickname", message);
                userMap.put("userName", message);
                userMap.put("name", message);
                userMap.put("avatar", usersDetail.getAvatar());
                userMap.put("flag", false);
            } else {
                UsersAuthentication findByUserId = usersAuthenticationService.getFindByUserId(parentUser.getId());
            if(findByUserId!=null) {
                if (LangValidUtils.getValid("ug")) {

                    userMap.put("name", StringUtils.isNotEmpty(findByUserId.getNameUg()) ? findByUserId.getNameUg() : findByUserId.getName());
                } else {
                    userMap.put("name", findByUserId.getName());
                }
            }
                userMap.put("nickname", parentUser.getNickname());
                userMap.put("userName", parentUser.getUserName());
                userMap.put("avatar", parentUser.getAvatar());
                userMap.put("id", parentUser.getId());

                userMap.put("flag", true);
            }

            map.put("parentUser", userMap);

        } else {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("name", message);
            userMap.put("nickname", message);
            userMap.put("userName", message);
            userMap.put("avatar", usersDetail.getAvatar());
            userMap.put("flag", false);
            userMap.put("id", 0);
            map.put("parentUser", userMap);
        }
        if (usersDetail.getAgentId() != null) {
            Map<String, Object> agent = agentService.findByMapId(usersDetail.getAgentId());
            map.put("agent", agent);
        }
        return map;

    }

    //phone
    @GetMapping("/byPhone")
    @ResponseBody
    public Result byPhone(@RequestParam(name = "phone", defaultValue = "") String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            boolean phoneValid = userService.isPhoneValid(phone);
            System.out.println("APPPPP:" + phoneValid);
            return phoneValid ? Result.failure() : Result.ok();
        } else {
            return Result.ok();
        }


    }

    //phone
    @GetMapping("/byIdCard")
    @ResponseBody
    public Result byIdCard(@RequestParam(name = "idcard", defaultValue = "") String idcard) {
        if (StringUtils.isNotEmpty(idcard)) {
            boolean idcardValid = usersAuthenticationService.isIdCardValid(idcard);
            System.out.println("APPPPP:" + idcardValid);
            return idcardValid ? Result.failure() : Result.ok();
        } else {
            return Result.ok();
        }


    }

    @PostMapping("/test")
    @ResponseBody
    public Result test() throws WxPayException {

        String orderNum = OrderUtils.getOrderNum(1L);
        //  String[] pay = weChatPayService.pay("jsapi", "TTTTTTT", "ccccccccccccccc", 100, "o7eTd4iOBdVxuWyo85fcl1NPYc2M");
        BigDecimal bigDecimal = new BigDecimal(0.01);
        // return Result.ok(pay);
        String openId = "o7eTd4pqafII42mNJ-eUMGiA237A";
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody("jjjjjjjjjj");
        orderRequest.setOutTradeNo(orderNum);
        orderRequest.setTotalFee(bigDecimal.multiply(new BigDecimal(100)).intValue());
        orderRequest.setSpbillCreateIp("127.0.0.1");
        //微信支付成功回调地址
        orderRequest.setNotifyUrl("http://serkol.5gzvip.91tunnel.com/api/payment/notify/order");
        orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
        orderRequest.setOpenid(openId);

        Object order = wxPayService.createOrder(orderRequest);
        return Result.ok(order);

    }




}
